<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model='search' style="width: 300px;" class="filter-item" :placeholder="$t('login.username')">
      </el-input>
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary" v-waves icon="el-icon-edit">{{$t('table.add')}}</el-button>
    </div>

    <el-table :data="searchData" :default-sort="{prop: 'username', order: 'descending'}" v-loading.body="listLoading" element-loading-text="Loading" border fit highlight-current-row style="width: 100%">
      <el-table-column align="center" label='ID' width="95">
        <template slot-scope="scope">
          {{scope.$index + 1}}
        </template>
      </el-table-column>
      <el-table-column prop="username" sortable label="用户名">
        <template slot-scope="scope">
          {{scope.row.username}}
        </template>
      </el-table-column>
      <el-table-column label="用户密码" width="200" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.password}}</span>
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="角色" width="160" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isAdmin | roleFilter">{{scope.row.isAdmin === 0 ? '普通用户':'管理员'}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="操作" width="230" align="center"> 
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">{{$t('table.edit')}}</el-button>
          <el-button size="mini" type="danger" @click="delUser(scope.row.username,'deleted')">{{$t('table.delete')}}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="loginRules" ref="dataForm" :model="temp" label-position="left" label-width="70px" >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="temp.username"  :disabled="inputDisable"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="temp.password"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{$t('table.cancel')}}</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createUser">{{$t('table.confirm')}}</el-button>
        <el-button v-else type="primary" @click="updateUser">{{$t('table.confirm')}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getUserList, creatUser, updateUser, delUser } from '@/api/user'
import { success, info_msg } from '@/utils/notify'
import { check } from '@/utils/resCheck'
import waves from '@/directive/waves'

export default {
  directives: {
    waves
  },
  data() {
    return {
      search: '',
      list: null,
      listLoading: true,
      dialogFormVisible: false,
      dialogStatus: '',
      downloadLoading: false,
      textMap: {
        update: '修改',
        create: '新建'
      },
      temp: {
        username: '',
        password: '',
        isAdmin: 0
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', message: this.$t('login.usernameval') }],
        password: [{ required: true, trigger: 'blur', message: this.$t('login.passwordval') }]
      }
    }
  },
  filters: {
    roleFilter(role) {
      const roleMap = {
        1: 'success',
        0: 'gray'
      }
      return roleMap[role]
    }
  },
  created() {
    this.fetchData()
  },
  computed: {
    inputDisable: function() {
      return this.dialogStatus === 'update'
    },
    searchData: function() {
      var search = this.search
      if (search) {
        return this.list.filter(function(product) {
          return Object.keys(product).some(function(key) {
            if (key === 'username') {
              return String(product[key]).toLowerCase().indexOf(search) > -1
            }
          })
        })
      }
      return this.list
    }
  },
  methods: {
    fetchData() {
      this.listLoading = true
      getUserList(this.listQuery).then(response => {
        this.list = response.userDtoLst
        this.listLoading = false
      })
    },
    resetTemp() {
      this.temp = {
        username: '',
        password: '',
        isAdmin: 0
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createUser() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          creatUser(tempData).then(response => {
            if (check(this, response) !== true) {
              this.dialogFormVisible = false
              return
            }
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            success(this, '创建成功')
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateUser() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateUser(tempData).then(response => {
            if (check(this, response) !== true) {
              this.dialogFormVisible = false
              return
            }
            this.dialogFormVisible = false
            this.fetchData()
            success(this, '更新成功')
          })
        }
      })
    },
    delUser(username, status) {
      this.$confirm('此操作将永久删除该用户,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delUser(username).then(response => {
          if (check(this, response) !== true) {
            this.dialogFormVisible = false
            return
          }
          this.fetchData()
          success(this, '删除成功')
        })
      }).catch(() => {
        info_msg(this, '已取消删除')
      })
    }
  }
}
</script>

